package com.linran.structure_algorithm.算法.lesson1_递归;

public class EightQueens {

    public int max = 8;
    //下标i代表i+1行，元素值value代表value+1列
    public int[] array = new int[max];
    public static int count = 0;
    public static int judgeCount = 0;

    public static void main(String[] args) {
        EightQueens eightQueens = new EightQueens();
        eightQueens.check(0);
        System.out.printf("共%d种解法", count);
        System.out.printf("共判断了%d次%n", judgeCount);
    }

    public void check(int n) {
        // 8个皇后放好，直接打印
        if (n == max) {
            print();
            return;
        }

        for (int i = 0; i < max; i++) {
            //先把当前皇后放到该行第i列
            array[n] = i;
            if (judge(n)) {
                //不冲突放第n+1个皇后
                check(n+1);
            }
        }
    }

    // 放置第n个皇后后查看棋盘是否冲突
    public boolean judge(int n) {
        judgeCount++;
        for (int i = 0; i < n; i++) {
            //1.array[i] == array[n]，检查列是否冲突
            //2.Math.abs(n - i) == Math.abs(array[n] - array[i]) 正反斜线是否冲突
            if (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {
                return false;
            }
        }
        return true;
    }

    //打印
    public void print() {
        count++;
        for (int i = 0; i < max; i++) {
            System.out.printf("%d", array[i]);
        }
        System.out.println();
    }
}
